module.exports = (app) => {
  const express = require("express");
  const router = express.Router({
    // 合并url参数
    mergeParams: true,
  });

  // 获取资源
  router.get("/getData", async (req, res) => {
    res.send("hello world");
  });

  // 创建
  // async 异步请求
  router.post("/", async (req, res) => {
    // 创建数据
    const model = await req.Model.create(req.body);
    // 发回给客户端
    res.send(model);
  });

  // 编辑
  router.put("/:id", async (req, res) => {
    // 根据id查找，在更新。
    const model = await req.Model.findByIdAndUpdate(req.params.id, req.body);
    // 发回给客户端
    res.send(model);
  });

  // 删除
  router.delete("/:id", async (req, res) => {
    // 根据id查找，在删除。
    await req.Model.findByIdAndDelete(req.params.id, req.body);
    // 发回给客户端
    res.send({
      success: true,
    });
  });

  // 查询列表
  router.get("/", async (req, res) => {
    const quetyOptions = {};
    if (req.Model.modelName === "Category") {
      quetyOptions.populate = "parent";
    }
    const items = await req.Model.find().setOptions({ quetyOptions }).limit(10);
    res.send(items);
  });

  // 根据id查询
  router.get("/:id", async (req, res) => {
    const model = await req.Model.findById(req.params.id);
    res.send(model);
  });

  app.use(
    "/admin/api/rest/:resource",
    async (req, res, next) => {
      const modelName = require("inflection").classify(req.params.resource);
      req.Model = require(`../../models/${modelName}`);
      next();
    },
    router
  );

  const multer = require("multer");
  const upload = multer({ dest: __dirname + "/../../uploads" });
  app.post("/admin/api/upload", upload.single("file"), async (req, res) => {
    const file = req.file;
    file.url = `http://localhost:3000/uploads/${file.filename}`
    res.send(file);
  });
};
